﻿Imports MS.Internal.Threading
Imports System.Threading

#If NETFX_CORE Then
Imports Runa.Foundation.Threading
#End If

Namespace Global.Runa.UI.Threading

    Friend Class DispatcherOperationFrame
        Inherits DispatcherFrame

        Private _operation As DispatcherOperation
        Private _waitTimer As Timer

        Public Sub New(ByVal op As DispatcherOperation, ByVal timeout As TimeSpan)
            MyBase.New(False)
            Me._operation = op
            AddHandler Me._operation.Aborted, New EventHandler(AddressOf Me.OnCompletedOrAborted)
            AddHandler Me._operation.Completed, New EventHandler(AddressOf Me.OnCompletedOrAborted)
            If (timeout.TotalMilliseconds > 0) Then
                Me._waitTimer = New Timer(New TimerCallback(AddressOf Me.OnTimeout), Nothing, timeout, TimeSpan.FromMilliseconds(-1))
            End If
            If (Me._operation.Status <> DispatcherOperationStatus.Pending) Then
                Me.Exit()
            End If
        End Sub

        Private Sub [Exit]()
            MyBase.Continue = False
            If (Not Me._waitTimer Is Nothing) Then
                Me._waitTimer.Dispose()
            End If
            RemoveHandler Me._operation.Aborted, New EventHandler(AddressOf Me.OnCompletedOrAborted)
            RemoveHandler Me._operation.Completed, New EventHandler(AddressOf Me.OnCompletedOrAborted)
        End Sub

        Private Sub OnCompletedOrAborted(ByVal sender As Object, ByVal e As EventArgs)
            Me.Exit()
        End Sub

        Private Sub OnTimeout(ByVal arg As Object)
            Me.Exit()
        End Sub

    End Class

End Namespace